package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.ContractAdapter
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.bean.old.CompanyContractListBean
import com.hinnotek.amoeba.databinding.ActivityContractBinding
import com.hinnotek.amoeba.ext.init
import com.hinnotek.amoeba.utilities.IntentUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.viewmodels.ContractViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener

/**
 * 合同Activity
 */
class ContractListActivity : BaseActivity<ActivityContractBinding>(), View.OnClickListener {

    private var myStrOption = mutableListOf<String?>("一厂", "二厂", "三厂")
    private var mySelectOption = 0
    private var mAdapter: ContractAdapter? = null
    private var customDialog: CustomDialog? = null
    private var pageNo = 1
    private val pageSize = 20


    val viewModel by viewModels<ContractViewModel>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("合同")

        setContentView(R.layout.activity_contract)
        initVew()
    }

    override fun initVew() {
        bindingView.recyclerView.init()
        bindingView.recyclerView.adapter = ContractAdapter().also { mAdapter = it }
        mAdapter?.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>, view: View?, position: Int ->
            val data = adapter.getItem(position) as CompanyContractListBean
            val bundle = Bundle()
            bundle.putInt("companyContractId", data.companyContractId)
            IntentUtils.startActivity(mContext, ContractDetailActivity::class.java, bundle)
        }
        bindingView.rbContractAdd.setOnClickListener { v: View? ->
            IntentUtils.startActivity(
                mContext,
                ContractSigningActivity::class.java
            )
        }
        customDialog = CustomDialog(mContext, "正在加载...")
        customDialog?.show()
        setData()
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.et_contract_name_select -> showListPickerView(true)
        }
    }

    //打开"选择"器
    private fun showListPickerView(isDialog: Boolean) {
        val pvOptions: OptionsPickerView<Any> =
            OptionsPickerBuilder(mContext, object : OnOptionsSelectListener {
                override fun onOptionsSelect(
                    v: View,
                    options1: Int,
                    options2: Int,
                    options3: Int
                ): Boolean {
                    bindingView.etContractNameSelect.setText(myStrOption[options1])
                    mySelectOption = options1
                    return false
                }
            })
                .setTitleText("请选择")
                .isDialog(isDialog)
                .setSelectOptions(mySelectOption)
                .build<Any>()
        pvOptions.setPicker(myStrOption.toList())
        pvOptions.show()
    }

    override fun setData() {
        //下拉刷新
        bindingView.refreshLayout.setOnRefreshListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo = 1
                    getCompanyContractPage()
                    refreshLayout.finishRefresh()
                }, 0
            )
        }
        //上拉加载
        bindingView.refreshLayout.setOnLoadMoreListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo++
                    getCompanyContractPage()
                }, 0
            )
        }
    }

    override fun onResume() {
        super.onResume()
        bindingView.refreshLayout.autoRefresh() //第一次进入触发自动刷新，演示效果
    }//将不会再次触发加载更多事件//setNoMoreData(false);//                    CompanyContractListBean companyContractListBean = JSON.parseObject(login_str, CompanyContractListBean.class);

    /**
     * app端获取合同列表分页接口
     */
    fun getCompanyContractPage(){

        val map = mutableMapOf<String,Any>().apply {
            put("pageNo", pageNo)
            put("pageSize", pageSize)
        }
        viewModel.getCompanyContractPage(getRequestBody(map)).observe(this,object : ObserverState<MutableList<CompanyContractListBean>>(){
            override fun onDataChange(data: MutableList<CompanyContractListBean>) {
                customDialog?.dismiss()
                if (pageNo == 1) {
                    when (getRefreshStatus(data.size)) {
                        Status.SUCCESS -> {
                            mAdapter?.setList(data)
                            if (data.size < pageSize) {
                                bindingView.refreshLayout.setEnableLoadMore(false)
                            } else {
                                bindingView.refreshLayout.setEnableLoadMore(true)
                            }
                            bindingView.refreshLayout.resetNoMoreData() //setNoMoreData(false);
                            bindingView.llStateful.showContent()
                        }
                        Status.EMPTY -> {
                            bindingView.llStateful.showEmpty()
                            bindingView.refreshLayout.setEnableLoadMore(false)
                        }
                        Status.ERROR -> showError()
                        Status.NO_NET -> showOffline()
                        else -> {
                        }
                    }
                    bindingView.refreshLayout.finishRefresh()
                } else {
                    if (data.size == 0) {
                        ToastUtils.showShort("数据全部加载完毕")
                        bindingView.refreshLayout.finishLoadMoreWithNoMoreData() //将不会再次触发加载更多事件
                    } else {
                        mAdapter?.addData(data)
                        bindingView.refreshLayout.finishLoadMore()
                    }
                }
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog?.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
        
    }


    private fun showOffline() {
        bindingView.llStateful.showOffline { v: View? -> bindingView.refreshLayout.autoRefresh() }
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private fun showError() {
        bindingView.llStateful.showError { v: View? -> bindingView.refreshLayout.autoRefresh() }
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private enum class Status {
        SUCCESS, EMPTY, ERROR, NO_NET
    }

    private fun getRefreshStatus(size: Int): Status {
        return if (size == 0) {
            Status.EMPTY
        } else Status.SUCCESS
    }
}